import { checkAuth, getUser } from '/store/actions'
import { $event } from '/utils'
import { GlobalData } from '/store/state'
import { userApi } from '/api/user'
import { activityApi } from '/api/activity'
import { isLogin } from '/store/mutations'

Page({
  data: {
    type: 0,
    loading: false,
    nav: [
      { title: '感兴趣', islastpage: false },
      { title: '想参加', islastpage: false },
    ],
    list: [[], []] as any[],
    id: 0,
    navigationHeight: 0,
  },
  async onLoad({ id }: any) {
    this.setData({
      id,
      navigationHeight: GlobalData.navigationHeight,
    }),
      $event.on('after:login', this, async () => {
        this.onPullDownRefresh()
        this.setData({
          user: getUser(),
        })
      })
    if (isLogin()) {
      this.setData({
        user: getUser(),
      })
    } else {
      await checkAuth()
    }

    this.onPullDownRefresh()
  },
  onReachBottom() {
    this.getData(true)
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    const {
      data: { type },
    } = this
    this.setData({
      [`nav[${type}].islastpage`]: false,
    })
    this.getData()
    wx.stopPullDownRefresh()
  },
  /**
   * tab切换
   * @param e
   */
  changeType(e: any) {
    const {
      target: {
        dataset: { type },
      },
    } = e
    if (type === this.data.type) return
    this.setData({
      type,
    })
    if (this.data.list[type].length === 0) {
      this.getData()
    }
  },
  async getData(more = false) {
    const {
      data: { type, nav, list, id, loading },
    } = this
    if (nav[type].islastpage) {
      wx.showToast({
        title: '已没有更多',
        icon: 'none',
      })
      return
    }
    if (loading) return
    this.setData({
      loading: true,
    })
    const methods = type === 0 ? 'getLikedList' : 'getWantJoinList'
    const lists = await activityApi[methods]({
      offset: more ? list[type].length : 0,
      event_id: id,
      limit: 15,
      with: 'user',
    })
    this.setData({
      [`list[${type}]`]: more ? [...list[type], ...lists] : lists,
      [`nav[${type}].isLastpage`]: lists.length < 15,
      loading: false,
    })
  },
  followAction(e: any) {
    const {
      target: {
        dataset: { user, index },
      },
    } = e
    const {
      data: { type },
    } = this
    let method = 'followUser' as keyof typeof userApi
    // 已关注状态
    if (user.has_follower) {
      method = 'unFollowUser'
    }
    userApi[method](user.id as never).then(() => {
      this.setData({
        [`list[${type}][${index}].user.has_follower`]: !user.has_follower,
      })
    })
  },
})
